<template>
  <div class="chartBox" ref="chartBox"></div>
</template>

<script>
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/legendScroll'
export default {
  props: {
    labelData: { // X轴各项名称
      type: Array,
      default: () => []
    },
    itemData: { // 数据集
      type: Array,
      default: () => []
    }
  },
  watch: {
    nowWaterData (val) {
      this.initChart()
    }
  },
  mounted () {
    this.initEchart()
    let myChart = echarts.init(this.$refs.chartBox)
    window.addEventListener('resize', () => {
      myChart.resize()
    }, false)
  },
  methods: {
    initEchart () {
      let myChart = echarts.init(this.$refs.chartBox)
      const series = this.itemData.map(item => {
        return {
          type: 'bar',
          name: item.name,
          data: [item.value]
        }
      })
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: (params, ticket, callback) => {
            const result = params.map(({marker, seriesName, data}, index) => {
              return `${marker} ${seriesName} ${data} `
            }).join('<br>')
            return `${result}`
          },
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: this.labelData,
          align: 'left',
          itemGap: 20
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            data: this.labelData
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: series
      })
    }
  }
}
</script>

<style lang="sass" scoped>
  .chartBox
    width: 100%
    height: 100%
</style>
